package cn.cmdr.config;

import cn.cmdr.pojo.Staff;
import cn.cmdr.service.PermissionService;
import cn.cmdr.service.StaffService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Configuration;

import java.util.List;

public class SmbmsRealm extends AuthorizingRealm {
    private StaffService staffService;
    private PermissionService permissionService;

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public void setStaffService(StaffService staffService) {
        this.staffService = staffService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Staff staff = (Staff) principalCollection.getPrimaryPrincipal();
        List<String> percodes = permissionService.getPerCode(staff.getRoleId());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(percodes);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String staffCode = (String) token.getPrincipal();
        Staff staff = staffService.getStaffCode(staffCode);
        if(staff==null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(staff,staff.getPassword(),ByteSource.Util.bytes(staff.getSalt()),getName());
        return simpleAuthenticationInfo;
    }
}
